package com.java.security.controller;

import com.java.security.entity.Role;
import com.java.security.entity.User;
import com.java.security.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jl
 * Created on 2020/7/20
 */
@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;

    @RequestMapping("/index")
    public String doLogin() {
        return "Index Page";
    }

    /**
     * 这三个测试接口，我们的规划是这样的：
     * /hello 是任何人都可以访问的接口
     * /admin/hello 是具有 admin 身份的人才能访问的接口
     * /user/hello 是具有 user 身份的人才能访问的接口
     * 所有 user 能够访问的资源，admin 都能够访问
     * 「注意第四条规范意味着所有具备 admin 身份的人自动具备 user 身份。」
     */

    @RequestMapping("/hello")
    public String hello() {
        helloService.hello();
        return "hello world";
    }

    @GetMapping("/admin/hello")
    public String admin() {
        // 获取当前用户,从Authentication中也能获取
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 如果用户修改了用户信息,再重新设置
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
        return "admin hello, 当前用户名: " + userDetails.getUsername() + ", 密码: " + userDetails.getPassword();
    }

    @GetMapping("/user/hello")
    public String user() {
        return "user hello";
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/user/info")
    public User getUserInfo(Authentication auth) {
        return (User) auth.getPrincipal();
    }
}
